//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends eui.UILayer {


    protected createChildren(): void {
        super.createChildren();

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            // egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());


        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {


        await this.loadResource()
        this.createGameScene();
        const result = await RES.getResAsync("description_json")
        this.startAnimation(result);
        await platform.login();
        const userInfo = await platform.getUserInfo();
        egret.log(userInfo);

    }

    private async loadResource() {
        try {
            const loadingView = new LoadingUI();
            this.stage.addChild(loadingView);
            await RES.loadConfig("resource/default.res.json", "resource/");
            await this.loadTheme();
            await RES.loadGroup("preload", 0, loadingView);
            this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }
    private timeOnEnterFrame = 0;
    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }
    private renderTexture: egret.RenderTexture;

    private textfield: egret.TextField;
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        let sky = this.createBitmapByName("bg_jpg");
        this.addChild(sky);
        let stageW = this.stage.stageWidth;
        let stageH = this.stage.stageHeight;
        var colorMatrix = [
            0.3, 0.6, 0, 0, 0,
            0.3, 0.6, 0, 0, 0,
            0.3, 0.6, 0, 0, 0,
            0, 0, 0, 1, 0
        ];
        var colorFlilter = new egret.ColorMatrixFilter(colorMatrix);
        var blurFliter = new egret.BlurFilter(10, 10);
        // sky.filters = [colorFlilter,blurFliter]

        sky.width = stageW;
        sky.height = stageH;

        let topMask = new egret.Shape();
        topMask.graphics.beginFill(0x000000, 0.5);
        topMask.graphics.drawRect(0, 0, stageW, 172);
        topMask.graphics.endFill();
        topMask.y = 10;
        this.addChild(topMask);

        // demo
        let shape1: egret.Shape = new egret.Shape();
        shape1.x = 0;
        shape1.y = stageH / 2;
        shape1.rotation = -90;

        shape1.graphics.beginFill(0x000000);

        shape1.graphics.lineStyle(10, 0x00ff00);
        shape1.graphics.drawRect(0, 0, 100, 172);

        shape1.graphics.endFill();

        this.addChild(shape1);

        // 
        var txInput: egret.TextField = new egret.TextField;
        txInput.type = egret.TextFieldType.INPUT;
        txInput.inputType = egret.TextFieldInputType.TEXT;
        txInput.text = "Input text:";
        txInput.width = 282;
        txInput.height = 43;
        txInput.x = 134;
        txInput.y = 400;
        txInput.textColor = 0x000000;
        /// 注意_container是事先建立好的一个显示容器，即 egret.Sprite，并且已经添加到显示列表中
        this.addChild(txInput);

        // MyGrid
        var _myGrid: MyGrid = new MyGrid();
        this.addChild(_myGrid);
        // 水平布局
        let _hLayout: hLayout = new hLayout();
        _hLayout.x = 100;
        _hLayout.y = stageH - 200;
        this.addChild(_hLayout);
        // 网格布局
        let _TileLayout = new TileLayout();
        _TileLayout.y = stageH - 500;
        this.addChild(_TileLayout);
        // 层叠容器
        let _viewStack = new ViewStackDemo();
        _viewStack.y =  100;
        this.addChild(_viewStack);
        // tabbar
        let _tabbar = new TabBarDemo();
        _tabbar.y = 900;
        this.addChild(_tabbar);
        // 创建空的可是对象
        let container: egret.DisplayObjectContainer = new egret.DisplayObjectContainer();
        container.x = 200;
        container.y = 200;
        this.addChild(container);

        let offsetX: number;
        let offsetY: number;
        // circle



        let circle: egret.Shape = new egret.Shape();
        circle.graphics.beginFill(0xff0000);
        circle.graphics.drawCircle(25, 25, 25);
        circle.graphics.endFill();
        container.addChild(circle);
        //给圆增加点击事件
        circle.touchEnabled = true;
        circle.addEventListener(egret.TouchEvent.TOUCH_TAP, function () {
            //把舞台左上角的坐标(0,0)转换为 container 内部的坐标
            var targetPoint: egret.Point = container.globalToLocal(0, 0);
            //重新定位圆，可以看到圆形移到了屏幕的左上角
            // circle.x = targetPoint.x;
            // circle.y = targetPoint.y;
        }, this)
        // 给圆增加拖动事件
        circle.addEventListener(egret.TouchEvent.TOUCH_MOVE, startMove, this)
        function startMove(e: egret.TouchEvent): void {
            offsetX = e.stageX - circle.x;
            offsetY = e.stageY - circle.y;
            this.stage.addEventListener(egret.TouchEvent.TOUCH_MOVE, onMove, this)
        }
        function onMove(e: egret.TouchEvent): void {
            //通过计算手指在屏幕上的位置，计算当前对象的坐标，达到跟随手指移动的效果
            circle.x = e.stageX - offsetX;
            circle.y = e.stageY - offsetY;
        }

        // 进度条
        this.initProgressBar();
        // list

        var scroller = new eui.Scroller();
        var list = new eui.List();

        var ac = new eui.ArrayCollection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
        scroller.x = 100;
        scroller.y = 400;
        list.dataProvider = ac;
        scroller.viewport = list;
        scroller.height = 200;
        this.addChild(scroller);
        scroller.addEventListener(egret.TouchEvent.TOUCH_BEGIN, () => { console.log("111 Scroller Begin") }, this);
        list.addEventListener(egret.TouchEvent.TOUCH_BEGIN, () => { console.log("111 List Begin") }, this);
        scroller.addEventListener(egret.TouchEvent.TOUCH_END, () => { console.log("222 Scroller END") }, this);
        list.addEventListener(egret.TouchEvent.TOUCH_END, () => { console.log("222 List END") }, this);
        scroller.addEventListener(egret.TouchEvent.TOUCH_TAP, () => { console.log("33 Scroller Tap") }, this);
        list.addEventListener(egret.TouchEvent.TOUCH_TAP, () => { console.log("33 List Tap") }, this);
        scroller.addEventListener(egret.TouchEvent.TOUCH_CANCEL, () => { console.log("44 Scroller cancel") }, this);
        list.addEventListener(egret.TouchEvent.TOUCH_CANCEL, () => { console.log("44 List cancel") }, this);
        var spr: egret.Sprite = new egret.Sprite();
        spr.graphics.beginFill(0x00ff00);
        spr.graphics.drawRect(0, 0, 100, 100);
        spr.graphics.endFill();
        this.addChild(spr);
        this.addEventListener(egret.Event.ENTER_FRAME, function () {
            var now = egret.getTimer();
            var time = this.timeOnEnterFrame;
            var pass = now - time;
            this.timeOnEnterFrame = egret.getTimer();
            if (spr.x < 300) {
                spr.x += 0.05 * pass;
            } else {

            }
        }, this);
        this.timeOnEnterFrame = egret.getTimer();


        // 动画
        this.renderTexture = new egret.RenderTexture();

        // 创建动画集
        let friendData = RES.getRes("girlFriend_json");
        let friendTexture = RES.getRes("girlFriend_png");
        let mcFactory: egret.MovieClipDataFactory = new egret.MovieClipDataFactory(friendData, friendTexture)
        // 获取某个动画
        let friendMc1: egret.MovieClip = new egret.MovieClip(mcFactory.generateMovieClipData('girlFriend'));
        friendMc1.x = 200;
        friendMc1.y = 600;
        this.addChild(friendMc1);
        friendMc1.play(3)
        friendMc1.touchEnabled = true;
        friendMc1.addEventListener(egret.TouchEvent.TOUCH_TAP, function (this, e) {
            if (friendMc1.isPlaying) {
                friendMc1.stop()
                this.renderTexture.drawToTexture(friendMc1);
            } else {
                friendMc1.play(-1)
            }

        }, this)
        // 截屏

        // 滤镜
        var color: number = 0x111111;        /// 光晕的颜色，十六进制，不包含透明度
        var alpha: number = 0.8;             /// 光晕的颜色透明度，是对 color 参数的透明度设定。有效值为 0.0 到 1.0。例如，0.8 设置透明度值为 80%。
        var blurX: number = 35;              /// 水平模糊量。有效值为 0 到 255.0（浮点）
        var blurY: number = 35;              /// 垂直模糊量。有效值为 0 到 255.0（浮点）
        var strength: number = 2;            /// 压印的强度，值越大，压印的颜色越深，而且发光与背景之间的对比度也越强。有效值为 0 到 255。暂未实现
        var quality: number = egret.BitmapFilterQuality.HIGH;        /// 应用滤镜的次数，建议用 BitmapFilterQuality 类的常量来体现
        var inner: boolean = false;            /// 指定发光是否为内侧发光，暂未实现
        var knockout: boolean = false;            /// 指定对象是否具有挖空效果，暂未实现
        var glowFilter: egret.GlowFilter = new egret.GlowFilter(color, alpha, blurX, blurY,
            strength, quality, inner, knockout);
        // 粒子系统
        var snowParticle = RES.getRes("snow_png");
        //获取配置
        var snowConfig = RES.getRes("snow_json");
        //创建 GravityParticleSystem
        var system = new particle.GravityParticleSystem(snowParticle, snowConfig);
        //启动粒子库
        system.start();
        //将例子系统添加到舞台
        this.addChild(system);
        let icon: egret.Bitmap = this.createBitmapByName("egret_icon_png");
        this.addChild(icon);
        icon.x = 526;
        icon.y = 183;
        icon.filters = [glowFilter]
        let line = new egret.Shape();
        line.graphics.lineStyle(2, 0xffffff);
        line.graphics.moveTo(0, 0);
        line.graphics.lineTo(0, 117);
        line.graphics.endFill();
        line.x = 172;
        line.y = 61;
        this.addChild(line);


        let colorLabel = new egret.TextField();
        colorLabel.textColor = 0xffffff;
        colorLabel.width = stageW - 172;
        colorLabel.textAlign = "center";
        colorLabel.text = "Hello Egret";
        colorLabel.size = 24;
        colorLabel.x = 172;
        colorLabel.y = 80;
        this.addChild(colorLabel);

        let textfield = new egret.TextField();
        this.addChild(textfield);
        textfield.alpha = 0;
        textfield.width = stageW - 172;
        textfield.textAlign = egret.HorizontalAlign.CENTER;
        textfield.size = 24;
        textfield.textColor = 0xffffff;
        textfield.x = 172;
        textfield.y = 135;
        this.textfield = textfield;

        let button = new eui.Button();
        button.label = "保存图片!";
        // (<eui.Label>button.labelDisplay).size = 50;
        button.horizontalCenter = 0;
        button.verticalCenter = 0;
        this.addChild(button);
        button.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onButtonClick, this);
        this.webSocket = new egret.WebSocket();
        this.webSocket.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onReceiveMessage, this);
        this.webSocket.addEventListener(egret.Event.CONNECT, this.onSocketOpen, this);
        this.webSocket.connect("echo.websocket.org", 80);
        this.addChild(this.getArcProgress());
    }
    private: Object;
    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name: string): egret.Bitmap {
        let result = new egret.Bitmap();
        let texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }
    /**
     * 描述文件加载成功，开始播放动画
     * Description file loading is successful, start to play the animation
     */
    private startAnimation(result: Array<any>): void {
        let parser = new egret.HtmlTextParser();

        let textflowArr = result.map(text => parser.parse(text));
        let textfield = this.textfield;
        let count = -1;
        let change = () => {
            count++;
            if (count >= textflowArr.length) {
                count = 0;
            }
            let textFlow = textflowArr[count];

            // 切换描述内容
            // Switch to described content
            textfield.textFlow = textFlow;
            let tw = egret.Tween.get(textfield);
            tw.to({ "alpha": 1 }, 200);
            tw.wait(2000);
            tw.to({ "alpha": 0 }, 200);
            tw.call(change, this);
        };

        change();
    }
    /**
     * 画进度条
     */
    private getArcProgress() {
        var shape: egret.Shape = new egret.Shape();
        shape.y = 200;
        var angle: number = 0;
        egret.startTick(function (timeStamp: number): boolean {
            angle += 1;
            changeGraphics(angle);
            angle = angle % 360;
            return true;
        }, this);
        return shape;
        function changeGraphics(angle) {
            shape.graphics.clear();
            shape.graphics.lineStyle(2, 0x0000ff, 1);
            shape.graphics.drawArc(50, 50, 50, 0, angle * Math.PI / 180, false);
            shape.graphics.endFill();
        }
    }
    /**
     * 点击按钮
     * Click the button
     */
    private onButtonClick(e: egret.TouchEvent) {
        this.removeChild(this.textfield)
        let panel = new eui.Panel();
        panel.title = "Title";
        panel.horizontalCenter = 0;
        panel.verticalCenter = 0;
        this.addChild(panel);
        this.renderTexture.saveToFile("image/png", "a/down.png");
    }

    private webSocket: egret.WebSocket;

    private onSocketOpen(): void {
        var cmd = "Hello Egret WebSocket22";
        console.log("连接成功，发送数据：" + cmd);
        this.webSocket.writeUTF(cmd);
    }
    private onReceiveMessage(e: egret.Event): void {
        var msg = this.webSocket.readUTF();
        console.log("收到数据：" + msg);
    }
    private pBar: eui.ProgressBar;
    private timerHandler(): void {
        this.pBar.value += 1;
        if (this.pBar.value >= 210) { this.pBar.value = 0; }
    }
    private initProgressBar(): void {
        this.pBar = new eui.ProgressBar();
        this.pBar.y = 300;
        this.pBar.maximum = 210;//设置进度条的最大值
        this.pBar.minimum = 0;//设置进度条的最小值
        this.pBar.width = 200;
        this.pBar.height = 30;
        this.addChild(this.pBar);
        this.pBar.value = 42;//设置进度条的初始值
        //用timer来模拟加载进度
        var timer: egret.Timer = new egret.Timer(10, 0);
        timer.addEventListener(egret.TimerEvent.TIMER, this.timerHandler, this);
        timer.start();
    }
}
